package com.hdax.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CustomRealm extends AuthorizingRealm {

    @Override
    public String getName() {
        return "CustomeRealm";
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //用户 查询    user:query
        //用户1 查询   user:query:1
        //更新所有用户  user:update:*
        //用户进行任意操作（增删改查） user:*

        //1. 能否获取认证之后的用户信息
        String realName = principalCollection.getPrimaryPrincipal().toString();

        //模拟数据查询得到的用户所有的角色及权限信息
        //角色
        List<String> roles = Arrays.asList("role1","role2");

        //权限
        List<String> permissions = Arrays.asList("app:search","app:update","app:delete","app:*");

        //2. 如何将获取的角色及权限进行存储
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(roles);
        authorizationInfo.addStringPermissions(permissions);


        return authorizationInfo;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //模拟数据库存储了一组用户信息
        String realName = "admin";
        String realPwd = "bd8af88c4bb25900af8de5fa548ee587";
        String salt = "qwerty";
        //获取用户输入的账号和密码
        String inputName = token.getPrincipal().toString();
        //判断用户名是否正确
        if(!realName.equals(inputName)){
            return null;
        }
        return new SimpleAuthenticationInfo(realName,realPwd, ByteSource.Util.bytes(salt),getName());//认证结束：
    }
}
